{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p style=\"text-align: center;font-size: 33px;font-weight:bold;\"> <span style=\"color:DarkGoldenrod\">&lt;&lt; C程序的基本要素 &gt;&gt;</span></p>\n",
    "<p style=\"text-align: center;font-size: 25px;font-weight:bold;\"> <span style=\"color:Goldenrod\">&lt;&lt; Programming Basics using C Language  &gt;&gt;</span></p>\n",
    "<p style=\"text-align: right; font-size:15px; font-weight:normal\">----千里之行，基于硅步</p>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* **条件判断语句与结构**\n",
    "* **分支判断语句与结构**\n",
    "* **三种循环结构[for(){}、while(){}、do{}while()]**\n",
    "* **continue与break**               "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* **条件判断语句(if)**\n",
    " * if(广义表达式){代码区}  &nbsp;&nbsp;&nbsp;&nbsp;  广义表达式可以为：{变量、常规表达式、**函数**} <br>**注意：常规表达式中可进行变量操作&nbsp;&nbsp;&nbsp;&nbsp;代码区只有在广义表达式为真的时候才会执行。**<br>\n",
    " * if(广义表达式){代码区1}else{代码区2} &nbsp;&nbsp;&nbsp;&nbsp;  当表达式为真，执行代码区1； 否则执行代码区2<br>\n",
    " * if(广义表达式) 语句; &nbsp;&nbsp;&nbsp;&nbsp; 当代码区极短，只有或可简写为一条语句时。 <br>\n",
    " * **语句;**与{代码区}可相互替换。<br>\n",
    " * if(){}else if(){}else if()...else;  连续判断语句。较为常用。**注意代码区内一定不要改变广义表达式中的变量**<br>\n",
    " * 没有else与else{}等价。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```C\n",
    "if(exprA(f(...))){codeblockA;}     //使用方程嵌入表达式，避免代码块的执行改变判断条件。\n",
    "else if(exprB(f(...))){codeblockB;}\n",
    "else if(exprC(f(...))){codeblockC;}\n",
    "else if(exprD(f(...))){codeblockD;}\n",
    "//else{codeblock0};\n",
    "//  codeblock[0,A~D]            只有一个会执行。如codeblockC;被执行，必然exprC为真值，且前向表达式均为0；\n",
    "//  [exprA,exprB,exprC,exprD] = [1,0,1,0]  只有codeblockA被执行；\n",
    "//                              [0,1,1,0]  只有codeblockB被执行， 均为expr[A~D]至少有一个为1的情况；\n",
    "//                              [0,0,0,0]  只有codeblock0被执行；\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```C\n",
    "float a;    \n",
    "if(a>7) printf(\"a is larger than 7\");\n",
    "else if(a>3) printf(\"a is in (3,7]\\n\");      //依然要注意a的类型范围\n",
    "else printf(\"a is equal or less than 3\");\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if(expA)\n",
    "    if(expB)\n",
    "        if(expC) 语句；            //  只有当expA expB expC 均为真才会执行语句。 等效于：if(expA&&expB&expC) 语句；"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```C\n",
    "if(a<100){\n",
    "    语句1;\n",
    "    if(a<10){\n",
    "       语句2;\n",
    "        if(a>0) 语句3;           //   当a满足什么条件，三条语句均执行。\n",
    "    }\n",
    "    \n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* **分支判断语句(switch)**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```C\n",
    "int a;\n",
    "scanf(\"%c\",&a);\n",
    "switch(a){         //一般只能作用于字符型变量, 或整形变量 \n",
    "    case 'a':                  if(a=='a'||a=='b') { if(a=='a') {}; 语句2;}\n",
    "    case 'b': 语句2 (,;) break ;               \n",
    ".......\n",
    "    default:  默认语句.\n",
    "} //版本1\n",
    "\n",
    "\n",
    "```\n",
    "```C\n",
    "int a;\n",
    "scanf(\"%c\",&a);\n",
    "switch(a){\n",
    "    case 'a':case 'b': case 'c': case'd': //在'b':后添加一条语句呢？\n",
    "    语句1; break ;\n",
    ".......                    \n",
    "    case 'f':case:'g'...... \n",
    "    语句n break;\n",
    "    case 'u':case 'x': case 'y': case'z':语句n;break; //去掉语句n与break，等同于删除该行\n",
    "    default: 语句;\n",
    "} //版本2 多个case执行同一条语句\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "//demo switch-case.\n",
    "#include <stdio.h>\n",
    "int main(){\n",
    "    int a;\n",
    "    scanf(\"a=%d\\n\",&a);\n",
    "    switch(a){\n",
    "        case 'a':printf(\"Do something accroding to your choice 'a'\\n\");break; //去掉break呢？\n",
    "        case 'b':printf(\"Do something accroding to your choice 'b'\\n\");break;\n",
    "        case 'c':printf(\"Do something according to your choice 'c'\\n\");break;\n",
    "        case 'd':printf(\"Do something according to your choice 'c'\\n\");break;    \n",
    "        default: printf(\"Not recognised %c!\\n\",a); \n",
    "}\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <stdio.h>\n",
    "int main() /* count digits, white space, others */\n",
    " {\n",
    " int c, i, nwhite, nother, ndigit[10];\n",
    " nwhite = nother = 0;\n",
    " for (i = 0; i < 10; i++)\n",
    " ndigit[i] = 0; i=0;\n",
    " char  ss[] = \"a10bb400\\t000642a\\n\";    \n",
    " while ((c=ss[i++])!='\\0') {\n",
    " switch (c) {\n",
    " case '0': case '1': case '2': case '3': case '4':\n",
    " case '5': case '6': case '7': case '8': case '9':\n",
    " ndigit[c-'0']++;\n",
    " break;\n",
    " case ' ':\n",
    " case '\\n':\n",
    " case '\\t':\n",
    " nwhite++;\n",
    " break;\n",
    " default:\n",
    " nother++;\n",
    " break;\n",
    " }\n",
    " }\n",
    " printf(\"digits =\");\n",
    " for (i = 0; i < 10; i++)\n",
    " printf(\" %d\", ndigit[i]);\n",
    " printf(\", white space = %d, other = %d\\n\",\n",
    " nwhite, nother);\n",
    " return 0;\n",
    " }"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* **for循环体** "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```C\n",
    "for(初始化体内变量;expr(i);//i++//i--//--i//++i//i+=n//i-=n){   //\n",
    "重复执行的代码区块\n",
    "}\n",
    "\n",
    "int main(){\n",
    "    int i=0;\n",
    "    for( ;;){\n",
    "    if(i>=4) break;\n",
    "    i++;    \n",
    "    };//   while(expr){};\n",
    "    \n",
    "// equal to    int i=0; do{state0;}while((i++)<5);//\n",
    "return -1;\n",
    "}    \n",
    "\n",
    "//缩写版：\n",
    "for(初始化体内变量;广义表达式;伴随操作)\n",
    "重复执行的单条语句；                 // 单条语句的含义： 完整的if模块、switch模块、循环体\n",
    "//以上为公司可以接受的C语言用法\n",
    "//注意：伴随操作的执行次序，每一次循环执行，均在‘重复执行的代码’与'重复执行的单条语句'后执行\n",
    "    \n",
    "/*以下代码在日常工作中可以不用，只可视为代码压缩，如同jquery的Release版本*/\n",
    "//空域版1：\n",
    "for(初始化体内变量|体外变量赋值|空；广义表达式|空；伴随操作|空) //可见C语言用法之灵活。    \n",
    "{重复执行的代码区块}|重复执行的单条语句；    //代码区块可以什么都没有；此时如下：\n",
    "//空域版2：\n",
    "for(初始化体内变量|体外变量赋值|空；广义表达式|空；伴随操作|空)； //注意分;号， 可配合逗号表达式\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**应确保循环体可结束**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int main(){\n",
    "    for(;;); //为空句无限循环\n",
    "    return 1;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <stdio.h>\n",
    "int main(){\n",
    "    //for(int i=1;printf(\"%d\\n\",i++),i++<10;); //尝试改写此代码，并查看运行结果是否与自己的设想一样。如不一样思考原因。\n",
    "    //printf(\"%d\\n\",i); //出了什么问题，编译检查错误还是运行错误？\n",
    "    \n",
    "    //龟兔赛跑  兔子不偷懒\n",
    "    //for(int r=0,t=30;printf(\"r=%d,t=%d\\n\",r+=3,++t),r<t;);\n",
    "    \n",
    "    \n",
    "    //鬼兔赛跑  兔子偷懒1\n",
    "    //for(int r=0,t=30;printf(\"r=%d,t=%d\\n\",r+=(r-t)<70?3:0,++t),t<500;); //好像出了问题！\n",
    "    \n",
    "    //鬼兔赛跑  兔子偷懒2\n",
    "    /*\n",
    "    int milestone=0;\n",
    "    for(int t=30,r=0;t<500;t++,printf(\"r=%d,t=%d\\n\",r,t)) //可用技巧，确保printf最后打印。\n",
    "    {\n",
    "        if(r-t>70) milestone=1; //此时怎样都不能用条件表达式。\n",
    "        if(!milestone) r+=3;\n",
    "    }\n",
    "    return 1;\n",
    "    \n",
    "}*/  //结合逗号表达式与for循环的句法约定可以写出同种功能代码的诸多版本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "while(广义表达式) 与 for(;广义表达式;) 等价。  //循环体{}内重来不定义变量，否则会导致变量的重复定义。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <stdio.h>\n",
    "int main(){\n",
    " int i=0;\n",
    " //while(printf(\"%d\\n\",i++),i<10);     //尝试修改++的位值。\n",
    " for(;printf(\"%d\\n\",i++),i<10;);       //等效代码\n",
    " return 1;   \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* **do{}while()循环体**<br>\n",
    "**do{语句1；语句2；...语句n;}while(广义表达式) 与<br>\n",
    "while(语句1，语句2,...语句n,广义表达式) 基本等价<br>\n",
    "广义表达式又分解为函数、变量、变量操作、常量的组合。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <stdio.h>\n",
    "int main(){\n",
    " //while();// 与for(;;);的唯一区别。\n",
    " //do{}while(); //\n",
    "    do{int a=0;}while(0);\n",
    "    for(;;){int a=0;break;};\n",
    "    return 0;   \n",
    "    \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* **continue 与 break**\n",
    "* **break**的作用：&nbsp;&nbsp;&nbsp;&nbsp;1.退出switch(){case...}；2. 退出循环体。\n",
    "* **continue**的作用：&nbsp;&nbsp;&nbsp;&nbsp; 直接进入下次循环而不执行后续循环体内语句。\n",
    "* **if 条件 break** &nbsp;&nbsp;&nbsp;&nbsp;  退出包含该if语句的循环体\n",
    "* **if 条件 continue**&nbsp;&nbsp;&nbsp;&nbsp; 等效 if(!条件){剩余代码}\n",
    "* switch(a) {case 1: case 2: case 3: ... case nn: break}  看到**break**退出循环吗？ 大陷阱。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "习题： 编写程序， （1） 打印100到1000以内所有满足各位和不为1且为该数约数的数值   \n",
    "                （2）  打印100到1000以内前五个满足各位和不为1且为该数约数的数值    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**总结如下：**<br>\n",
    "* **重点内容为：for循环体内伴随操作与代码区间的执行次序， 多个case的用法**\n",
    "* **没听说有人能够cover掉所有用法，用自己熟悉的**\n",
    "* **工作中应不断总结，提出自己的代码哲学（该怎样，不该怎样）**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include<stdio.h>\n",
    "int main(){\n",
    "    int k=0;\n",
    "    for(int i=100;i<=1000;i++){\n",
    "       k=0;\n",
    "       for(int j=i;j>0;j/=10) k=k+j%10;\n",
    "       if(i%k==0&&k!=1)  printf(\"%d,%i\\n\",k,i);\n",
    "   k=0;\n",
    "   } \n",
    "return 0;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include<stdio.h>\n",
    "int main(){\n",
    "    int k=0;\n",
    "    for(int i=100;i<=1000;i++){\n",
    "       k=0;\n",
    "       for(int j=i;j>0;j/=10) k=k+j%10;\n",
    "       if(i%k==0&&k!=1)  {printf(\"%d,%i\\n\",k,i);break;}\n",
    "   } \n",
    "return 0;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include<stdio.h>\n",
    "int main(){\n",
    "    int k=0;\n",
    "    for(int i=100;i<=1000;i++){\n",
    "       k=0;\n",
    "       for(int j=i;j>0;j/=10) k=k+j%10;\n",
    "       if(k%3==0||k%5==0||k%2==0) continue;\n",
    "       if(i%k==0&&k!=1)  printf(\"%d,%i\\n\",k,i);\n",
    "    } \n",
    "return 0;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "//%cflags:-lm\n",
    "#include <math.h>\n",
    "#include <time.h>\n",
    "#include <stdio.h>\n",
    "double mysqrt(double x)  //newtons method\n",
    "{\n",
    "     \n",
    "    if(x<0)  return 0.0/0.0;\n",
    "    if(x==0) return 0;\n",
    "    double guess=x/2,delta = (guess*guess-x)/(2*guess);guess=guess-delta,delta = delta>0?delta:(-delta);\n",
    "    while(delta>1e-16)  delta = (guess*guess-x)/(2*guess),guess=guess-delta;\n",
    "    if(delta<0) guess=guess-delta/2;\n",
    "    else guess=guess-delta;\n",
    "    return guess;\n",
    "}\n",
    "double mysqrtv2(register double y) //newtons method with register\n",
    "{\n",
    "    if(y<0)  return 0.0/0.0;\n",
    "    if(y==0) return 0;\n",
    "    register double x,delta;\n",
    "    for(x=y/2,delta=(x-y/x)/2;delta>1e-9||delta<-1e-9;x-=delta,delta=(x-y/x)/2);\n",
    "    return x;\n",
    "}\n",
    "//babylognian\n",
    "double mysqrtv3(double y)  \n",
    "{\n",
    "    if(y<0)  return 0.0/0.0; \n",
    "    if(y==0) return 0;\n",
    "    double x;\n",
    "    for(x=(long)(y+1.0);(y-x*x)>1e-9||(y-x*x)<-1e-9;x=(y/x+x)/2);\n",
    "    return x;\n",
    "}\n",
    "\n",
    "//Bakhshali\n",
    "float mysqrtv4(float y)\n",
    "{\n",
    "    if(y<0)  return 0.0/0.0; \n",
    "    if(y==0) return 0;\n",
    "    float x,a;\n",
    "    for(x=(long)(y+1.0),a=(y/x-x)/2;a>1e-7||a<-1e-7;x+=a-a*a/2/(x+a),a=(y/x-x)/2);\n",
    "    return x;\n",
    "}\n",
    "\n",
    "//useapprox log2(x) \n",
    "const int bias = (1<<29)-(1<<22)-0x4B0D2;\n",
    "float mysqrtv5(float y)\n",
    "{\n",
    "    if(y<0)  return 0.0/0.0; \n",
    "    if(y==0) return 0;\n",
    "    int appr=*(int*)&y;\n",
    "    appr >>=1;\n",
    "    appr += bias;\n",
    "    //float x=*(float*)&appr;x=(y/x+x)/2,x=(y/x+x)/2;\n",
    "    return *(float*)&appr;\n",
    "}\n",
    "// asm still not faster than standard library\n",
    " double  mysqrtv6(double n)\n",
    "{\n",
    "   __asm__ (\"fldl %0;\"\n",
    "            \"fsqrt;\"\n",
    "            \"fstpl %0\" : \"+m\"(n));\n",
    "  return n;   \n",
    "}\n",
    "\n",
    "int main(){\n",
    "    clock_t t1 =clock();\n",
    "    for(int i=1;i<100000;i++)\n",
    "    sqrt(i+0.234);\n",
    "    clock_t t2 = clock();\n",
    "    for(int i=1;i<100000;i++)\n",
    "    mysqrtv6(i+0.234);\n",
    "    clock_t t3 = clock();\n",
    "    printf(\"standard %lf,my %lf\\n\",(double)(t2-t1),(double)(t3-t2));\n",
    "    for(int i=1;i<100;i++)\n",
    "    printf(\"%f,%f\\n\",sqrt(1.0/i),mysqrtv6(1.0/i));\n",
    "    return -1;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C",
   "language": "c",
   "name": "c"
  },
  "language_info": {
   "file_extension": ".c",
   "mimetype": "text/plain",
   "name": "c"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
